package org.example.aicloud.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.aicloud.entity.User;
import org.example.aicloud.entity.dto.UserDTO;
import org.example.aicloud.service.IUserService;
import org.example.aicloud.util.NameUtil;
import org.example.aicloud.util.ResultAjax;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.lang.model.element.Name;
import java.util.HashMap;

@RestController
@Tag(name = "用户管理")
@RequestMapping("/user")
public class UserController {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private IUserService userService;


    @Value("${jwt.secret}")
    private String jwtSecret;

    @PostMapping("/login")
    public ResultAjax login(@Validated UserDTO userDTO, HttpServletRequest request){


        //验证图片验证码
        String redisCaptchaKey = NameUtil.getCaptchaName(request);
        String redisCaptcha = (String) redisTemplate.opsForValue().get(redisCaptchaKey);
        if (redisCaptcha == null || !userDTO.getCaptcha().equalsIgnoreCase(redisCaptcha)) {  //验证码忽略大小写
            return ResultAjax.error("输入验证码错误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("username",userDTO.getUsername());
         User user = userService.getOne(queryWrapper);
         if (user != null && passwordEncoder.matches(userDTO.getPassword(),user.getPassword())) {
             //生成JWT
             HashMap<String,Object> payLoad = new HashMap<>();
             payLoad.put("uid",user.getUid());
             payLoad.put("username",user.getUsername());
             HashMap<String,String> result = new HashMap<>();
             result.put("jwt",JWTUtil.createToken(payLoad, jwtSecret.getBytes()));
             result.put("username",user.getUsername());
             return ResultAjax.success(result);
         }
         return ResultAjax.error("用户名或密码错误");
    }

   @PostMapping("/register")
  public ResultAjax add(@Validated User user) {
        //将密码进行加盐处理
     user.setPassword(passwordEncoder.encode(user.getPassword()));

    boolean result = userService.save(user);
    if (result) {
      return ResultAjax.success(result);
    }

    return ResultAjax.error("未知错误");
  }

  @Operation(summary = "测试")
  @PostMapping("/test")
  @Parameters( {
          @Parameter(name = "msg", description = "测试参数")
  })
  public String logout(String msg) {
        return "ok: " + msg;
  }
}
